<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      body {
        margin: 0;
        padding: 0;
      }
      .content {
        width: 100vw;
        height: 100vh;
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding: 0 10%;
        box-sizing: border-box;
        gap: 20px;
      }
      table {
        border-collapse: collapse;
        width: 100%;
      }
      th,
      td {
        border: 1px solid black;
        padding: 8px;
        text-align: left;
      }
      .pagination {
        text-align: center;
      }

      #userForm {
        display: flex;
        flex-direction: column;
        gap: 10px;
      }
    </style>
  </head>
  <body>
    <div class="content">
      <div>
        <input id="search_input" type="text" placeholder="账号查询" />
        <button onclick="getTableData()">查询</button>
        <button onclick="addUser()">添加</button>
      </div>
      <table>
        <thead>
          <tr>
            <th>账号</th>
            <th>手机号</th>
            <th>邮箱</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
      <div class="pagination">共有：<span id="count"></span>条</div>
    </div>

    <dialog id="addUser">
      <form id="userForm" action="javascript:;">
        <input type="text" id="id" name="id" hidden />

        <label for="username">账号：</label>
        <input type="text" id="username" name="user_name" />

        <div id="passwordDiv">
          <div>
            <label for="password">密码：</label>
          </div>
          <input type="password" id="password" name="password" />
        </div>

        <label for="phone">手机号：</label>
        <input type="text" id="phone" name="phone" />

        <label for="email">邮箱：</label>
        <input type="email" id="email" name="email" />

        <button onclick="submitForm()">提交</button>
        <button
          type="button"
          onclick="document.querySelector('#addUser').close()"
        >
          取消
        </button>
      </form>
    </dialog>
  </body>
  <script>
    (function () {
      getTableData();
    })();

    function getTableData() {
      let user_name = document.getElementById("search_input").value;
      fetch(`http://localhost:3000/user/getAllUsers?user_name=${user_name}`)
        .then((res) => res.json())
        .then((res) => {
          let tbody = document.querySelector("tbody");
          let count = document.querySelector("#count");
          count.innerHTML = res.data.length;
          tbody.innerHTML = "";
          res.data.forEach((item) => {
            let tr = document.createElement("tr");
            tr.innerHTML = `
              <td>${item.user_name}</td>
              <td>${item.phone}</td>
              <td>${item.email}</td>
              <td>${parseTime(item.create_time)}</td>
              <td>
                <button onclick="deleteUser(${item.id})">
                  刪除
                </button>
                <button onclick="updateUser(${item.id})">
                  修改
                </button>
              </td>
            `;
            tbody.appendChild(tr);
          });
        });
    }

    function parseTime(time) {
      return new Date(time).toLocaleString().replace(/\//g, "-");
    }

    function addUser() {
      let dialog = document.querySelector("#addUser");
      dialog.showModal();
      let userForm = document.querySelector("#userForm");
      userForm.reset();
      document.querySelector("#id").value = "";
      document.querySelector("#passwordDiv").style.display = "block";
    }

    async function submitForm(item) {
      // 获取表单数据
      const formData = new FormData(document.querySelector("#userForm"));
      const data = {};
      formData.forEach((value, key) => {
        data[key] = value;
      });
      // 自定义处理逻辑
      console.log("Form submitted with data:", data);
      let res;
      if (data.id) {
        res = await fetch("http://localhost:3000/user/updateUser", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data),
        }).then((res) => res.json());
      } else {
        res = await fetch("http://localhost:3000/user/addUser", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data),
        }).then((res) => res.json());
      }

      if (res.code === 200) {
        document.querySelector("#addUser").close();
        getTableData();
      } else {
        alert(res.message);
      }
    }

    // 删除用户
    function deleteUser(id) {
      let isRelay = confirm("确定要删除吗？");
      if (!isRelay) return;
      fetch(`http://localhost:3000/user/deleteUser?id=${id}`, {
        method: "POST",
      })
        .then((res) => res.json())
        .then((res) => {
          getTableData();
        });
    }

    // 修改用户
    function updateUser(id) {
      fetch(`http://localhost:3000/user/getUserById?id=${id}`)
        .then((res) => res.json())
        .then((res) => {
          console.log(res.data);

          let dialog = document.querySelector("#addUser");
          dialog.showModal();
          document.querySelector("#username").value = res.data.user_name;
          document.querySelector("#phone").value = res.data.phone;
          document.querySelector("#email").value = res.data.email;
          document.querySelector("#id").value = res.data.id;
          // 隐藏密码输入框
          document.querySelector("#passwordDiv").style.display = "none";
        });
    }
  </script>
</html>
